﻿using Newtonsoft.Json;
using SmartWaterMointerCenter.Models;
using SmartWaterMointerCenter.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace SmartWaterMointerCenter
{
    public partial class FrmSetting : Form
    {
        public FrmSetting()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void FrmSetting_Load(object sender, EventArgs e)
        {
            // 是否有存储配置的文件夹。如果没有则创建
            if (!Directory.Exists(CommonHelper.configFilePath))
            {
                Directory.CreateDirectory(CommonHelper.configFilePath);
                // 加载楼层及从站下拉框

            }
            if (CommonHelper.floorList.Count > 0)
            {
                BindCboFloor();
            }
            if (CommonHelper.slaveList.Count > 0)
            {
                BindCboSlave();
            }
            cboGrades.SelectedIndex = 0;
        }

        private void BindCboSlave()
        {
            cboSlaves.DataSource = null;
            cboSlaves.DisplayMember = "SlaveId";
            //cboSlaves.ValueMember = "SlaveId";
            cboSlaves.DataSource = CommonHelper.slaveList;
        }

        private void BindCboFloor()
        {
            cboFloor.DataSource = null;
            cboFloor.DisplayMember = "FloorName";
            cboFloor.ValueMember = "FloorNo";
            cboFloor.DataSource = CommonHelper.floorList;
        }

        private void btnConnSlaveSet_Click(object sender, EventArgs e)
        {
            // 程序运行工具 progress 调用配置工具的exe,运行起来
            string exePath = Application.StartupPath + "/tools/ConfigPortAndSlaves.exe";
            if (File.Exists(exePath))
            {
                Process tool = new Process();
                tool.StartInfo.FileName = exePath;
                tool.Start();
                tool.WaitForExit();
                if (tool.ExitCode != 0)
                {
                    CommonHelper.CreateConn();
                    CommonHelper.LoadSlaveList();
                    if (CommonHelper.slaveList.Count > 0)
                    {
                        BindCboSlave();
                    }
                }
            }

        }

        private void btnFloorSave_Click(object sender, EventArgs e)
        {
            // 信息接受
            int floorNo = txtFloorNo.Text.GetInt();
            string floorName = txtFloorName.Text.Trim();
            // 信息检查
            if (floorNo <= 0)
            {
                MessageHelper.Error("楼层信息", "请输入大于0的楼层编号");
                txtFloorNo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(floorName))
            {
                MessageHelper.Error("楼层信息", "请输入楼层名称");
                txtFloorName.Focus();
                return;
            }
            // 信息封装
            FloorInfo floor = null;
            if (CommonHelper.floorList.Count > 0)
            {
                floor = CommonHelper.floorList.Find(e => e.FloorNo == floorNo);
            }
            bool isUpdate = false;
            if (floor != null)
            {
                if (floor.FloorName != floorName) { floor.FloorName = floorName; isUpdate = true; }
            }
            else
            {
                floor = new FloorInfo() { FloorNo = floorNo, FloorName = floorName };
                CommonHelper.floorList.Add(floor);
                isUpdate = true;
            }
            // 提交处理- 添加、修改、写入文件
            if (!isUpdate)
            {
                SaveFloorInfo();
            }

        }


        private void SaveFloorInfo()
        {
            string json = JsonConvert.SerializeObject(CommonHelper.floorList);
            File.WriteAllText(CommonHelper.floorPath, json);
            MessageHelper.Success("楼层保存", "楼层信息保存成功");
            BindCboFloor();
            CommonHelper.IsFloorUpdated = true;
        }

        private void deleteFloorBtn_Click(object sender, EventArgs e)
        {
            int floorNo = txtFloorNo.Text.GetInt();
            if (floorNo > 0 && CommonHelper.floorList.Count > 0)

            {
                FloorInfo delFloor
                    = CommonHelper.floorList.Find(e => e.FloorNo == floorNo);
                if (delFloor != null)
                {
                    if (MessageHelper.Question("楼层删除", $"你要删除{delFloor.FloorName}信息么？") == DialogResult.OK)
                    {
                        CommonHelper.floorList.Remove(delFloor);
                        SaveFloorInfo();
                    }
                }
            }
            else
            {
                MessageHelper.Error("楼层删除", "该楼层不存在");
            }
        }
        // 选择等级，加载已有设置
        private void cboGrades_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboGrades.SelectedItem != null)
            {
                int grade = cboGrades.SelectedItem.ToString().GetInt();
                LevelInfo levelInfo = CommonHelper.levelList.Find(e => e.Grade == grade);
                if (levelInfo != null)
                {
                    txtMinVal.Text = levelInfo.Min.ToString();
                    if (levelInfo.Max.HasValue)
                    {
                        txtMaxVal.Text = levelInfo.Max.ToString();
                    }
                    else
                    {
                        txtMaxVal.Text = "";
                    }
                }

            }
        }
        XmlDocument docLevel = new XmlDocument(); // 操作文档对象
        // 等级设置保存
        private void btnGradesSave_Click(object sender, EventArgs e)
        {
            // 信息接受、检查
            int grade = cboGrades.Text.GetInt();
            decimal minVal = 0;
            if (string.IsNullOrEmpty(txtMinVal.Text))
            {
                MessageHelper.Error("等级设置", "请设置用水等级");
                txtMinVal.Focus();
                return;
            }
            minVal = txtMinVal.Text.GetDecimal();
            decimal? maxVal = null;
            if (!string.IsNullOrEmpty(txtMaxVal.Text))
            {
                maxVal = txtMaxVal.Text.GetDecimal();
                if (maxVal < minVal)
                {
                    MessageHelper.Error("等级设置", "用水等级的高值不能低于低值");
                    txtMaxVal.Focus();
                    return;
                }
            }
            if (File.Exists(CommonHelper.levelPath))
            {

                /// 区分Load和loadXML
                /// Load：支持xml路径、文件流、不支持XML文本；
                /// LoadXml：支持XML文本，不支持xml路径。
                docLevel.Load(CommonHelper.levelPath);
            }
            else
            {
                XMLHelper.CreateNewXml(docLevel, "WaterLevels");
            }
            var root = docLevel.DocumentElement;// 根节点
            if (CommonHelper.levelList.Find(e => e.Grade == grade) != null)
            {
                LevelInfo levelInfo = CommonHelper.levelList.Find(e => e.Grade == grade);
                // 更新
                levelInfo.Min = minVal;
                levelInfo.Max = maxVal;
                // 更新节点
                var node = root.SelectSingleNode($"Level[@grade='{grade}']");
                if (node != null)
                {
                    node.SelectSingleNode("Min").InnerText = minVal.ToString();
                    if (levelInfo.Max.HasValue)
                    {
                        node.SelectSingleNode("Max").InnerText = maxVal.ToString();
                    }
                }
            }
            else
            {
                LevelInfo level = new LevelInfo() { Grade = grade, Min = minVal, Max = maxVal };
                CommonHelper.levelList.Add(level);
                XmlElement eleLevel = XMLHelper.AddElement(docLevel, "Level", root);
                XMLHelper.AddAttribute(docLevel, "grade", eleLevel, grade.ToString());
                XMLHelper.AddElement(docLevel, "Min", eleLevel, minVal.ToString());// 添加Min 子节点
                if (maxVal.HasValue)
                {
                    XMLHelper.AddElement(docLevel, "Max", eleLevel, maxVal.ToString());// 添加Max子节点
                }
            }
            docLevel.Save(CommonHelper.levelPath);
            MessageHelper.Success("用水等级设置", "用水等级设置保存成功");
        }
        // 保存住户信息配置
        private void btnResidentSave_Click(object sender, EventArgs e)
        {
            // 信息接收
            int residentNo = txtResidentNo.Text.GetInt();
            string residentName = txtResidentName.Text.Trim();
            int floorNo = cboFloor.SelectedValue.ToString().GetInt();
            byte slaveId = cboSlaves.Text.GetByte();
            ushort addr = txtAddress.Text.GetUshort();
            // 信息检查
            if (residentNo < 0)
            {
                MessageHelper.Error("住户信心", "住户编号不能小于0");
                txtFloorNo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(residentName))
            {
                MessageHelper.Error("住户信心", "请输入住户名");
                txtResidentName.Focus();
                return;
            }
            if (addr < 0)
            {
                MessageHelper.Error("住户信心", "存储器的地址不能小于0！");
                txtAddress.Focus();
                return;
            }
            // 信息保存  
            bool isUpdate = false;
            ResidentInfo residentInfo = CommonHelper.residentList.Find(e => e.ResidentNo == residentNo);
            if (residentInfo != null && (residentInfo.ResidentName != residentName || residentInfo.FloorNo != floorNo || residentInfo.SlaveId != slaveId || residentInfo.Address != addr))
            {
                residentInfo.ResidentName = residentName;
                residentInfo.FloorNo = floorNo;
                residentInfo.SlaveId = slaveId;
                residentInfo.Address = addr;
                isUpdate = true;
            }
            else if (residentInfo == null)
            {
                residentInfo = new ResidentInfo()
                {
                    ResidentNo = residentNo,
                    ResidentName = residentName,
                    FloorNo = floorNo,
                    SlaveId = slaveId,
                    Address = addr

                };
                isUpdate = true;
                CommonHelper.residentList.Add(residentInfo);
            }
            // 信息写入
            if (isUpdate)
            {
                string json = JsonConvert.SerializeObject(CommonHelper.residentList);
                File.WriteAllText(CommonHelper.residentPath, json);
                MessageHelper.Success("住户信心", "用户信息保存成功");
                CommonHelper.IsResidentUpdated = true;
            }
        }
    }
}
